package com.sky.Task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;

    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void processDeliveryOrder(){
        log.info("定时处理处于派送中的订单:{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        Orders orders = Orders
                .builder()
                .orderTime(time)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        List<Orders> list = orderMapper.selectByOrder(orders);
        if (list.isEmpty()) return;
        List<Orders> longList = new ArrayList<>();
        for (Orders o :list){
            orders = Orders
                    .builder()
                    .id(o.getId())
                    .status(Orders.COMPLETED)
                    .build();
            longList.add(orders);
        }
        orderMapper.updateByIds(longList);
    }


    @Scheduled(cron = "0 * * * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void processTimeoutOrder(){
        log.info("定时处理超时订单:{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        Orders orders = Orders
                .builder()
                .orderTime(time)
                .status(Orders.PENDING_PAYMENT)
                .build();
        List<Orders> list = orderMapper.selectByOrder(orders);
        if (list.isEmpty()) return;
        List<Orders> longList = new ArrayList<>();
        for (Orders o :list){
            orders = Orders
                    .builder()
                    .id(o.getId())
                    .status(Orders.CANCELLED)
                    .build();
            longList.add(orders);
        }
        orderMapper.updateByIds(longList);
    }
}
